package com.breakfast.fun.ui.user.info;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.data.entity.user.UserData;
import com.breakfast.fun.ui.user.UserFragment;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.SharedUtil;
import com.breakfast.fun.util.T;
import com.breakfast.fun.view.widget.TitleBarView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;

public class UserInfoActivity extends BaseActivity<UserInfoPresenter, UserInfoModel> implements UserInfoContract.View {

    @Bind(R.id.tbv_user_info)
    TitleBarView mTbvUserInfo;
    @Bind(R.id.iv_user_info_head)
    ImageView mIvUserInfoHead;
    @Bind(R.id.et_user_info_name)
    TextView mTvUserInfoName;
    @Bind(R.id.rl_user_info_name)
    RelativeLayout mRlUserInfoName;
    @Bind(R.id.tv_user_info_sex)
    TextView mTvUserInfoSex;
    @Bind(R.id.iv_user_info_arrow2)
    ImageView mIvUserInfoArrow2;
    @Bind(R.id.rl_user_info_sex)
    RelativeLayout mRlUserInfoSex;
    @Bind(R.id.iv_user_info_arrow4)
    ImageView mIvUserInfoArrow4;
    @Bind(R.id.rl_user_info_pwd)
    RelativeLayout mRlUserInfoPwd;
    @Bind(R.id.ll_user_info)
    LinearLayout mLlUserInfo;
    @Bind(R.id.btn_user_info_save)
    Button mBtnUserInfoSave;
    @Bind(R.id.rl_user_info_head)
    RelativeLayout mRlUserInfoHead;
    @Bind(R.id.tv_user_info_birthday)
    TextView mTvUserInfoBirhthday;
    @Bind(R.id.rl_user_info_birthday)
    RelativeLayout mRlUserInfoBirthday;

    private PopupWindow mUserHeadPop;
    private View mPopView;

    private PopupWindow mUserSexPop;
    private View mSexView;

    // 拍照
    private static final String PHOTO_TYPE = "image/*";
    private static final int PHOTO_ZOOM = 1;
    private static final int IMAGE_RESULT = 2;
    private static final int PHOTO_GRAPH = 3;
    private Bitmap bmp;
    File cropfile;

    private long currentTime;
    private DatePickerDialog mDatePickerDialog;
    private String birthdayStr = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    public void initView() {
        mTbvUserInfo.setTitleNoRight("个人信息");
        mTbvUserInfo.setBack(this);

        UserData userData = Constant.getUserData();
        mTvUserInfoName.setText(userData.getNickname());
        mTvUserInfoSex.setText(userData.getSex());
        mTvUserInfoBirhthday.setText(userData.getBirthday());

        Glide.with(this).load(userData.getPhoto()).placeholder(R.drawable.ic_user_head)
                .error(R.drawable.ic_user_head).into(mIvUserInfoHead);

        mRlUserInfoHead.setOnClickListener(v -> {
            showPop();
        });

        mRlUserInfoSex.setOnClickListener(v -> {
            showSexPop();
        });

        mRlUserInfoPwd.setOnClickListener(v -> {
            modifyPwd();
        });

        mBtnUserInfoSave.setOnClickListener(v -> {
            saveInfo();
        });

        mRlUserInfoBirthday.setOnClickListener(v -> {
            showBirthday();
        });
    }

    private void saveInfo() {
        String birthdayStr = "";
        if (!mTvUserInfoBirhthday.getText().toString().equals("填写送生日礼物噢！")) {
            birthdayStr = mTvUserInfoBirhthday.getText().toString();
        }
        presenter.saveInfo(mTvUserInfoName.getText().toString(),
                mTvUserInfoSex.getText().toString(), birthdayStr);
    }

    private void modifyPwd() {
        Intent intent = intent = new Intent(this, UserModifyPwdActivity.class);
        startActivity(intent);
    }

    private void showSexPop() {
        mSexView = LayoutInflater.from(this).inflate(R.layout.widget_pop_sex, null);
        mUserSexPop = new PopupWindow(mSexView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        final ViewHolderSex sexHolder = new ViewHolderSex(mSexView);

        sexHolder.mTvPopSexCancel.setOnClickListener(v -> {
            mUserSexPop.dismiss();
        });
        sexHolder.mTvPopSexNan.setOnClickListener(v -> {
            mUserSexPop.dismiss();
            mTvUserInfoSex.setText("男");
        });
        sexHolder.mTvPopSexNv.setOnClickListener(v -> {
            mUserSexPop.dismiss();
            mTvUserInfoSex.setText("女");
        });

        mUserSexPop.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#70000000")));
        mUserSexPop.showAtLocation(mLlUserInfo, Gravity.BOTTOM, 0, 0);
        mUserSexPop.setAnimationStyle(R.style.app_pop);
        mUserSexPop.setOutsideTouchable(true);
        mUserSexPop.setFocusable(true);
        mUserSexPop.update();
        mUserSexPop.showAsDropDown(mPopView);
    }

    private void showPop() {
        mPopView = LayoutInflater.from(this).inflate(R.layout.widget_pop_head, null);
        mUserHeadPop = new PopupWindow(mPopView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        final ViewHolder holder = new ViewHolder(mPopView);
        holder.mTvUserHeadCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUserHeadPop.dismiss();
            }
        });

        holder.mTvUserHeadCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUserHeadPop.dismiss();
                File lcoalfile = new File(Environment.getExternalStorageDirectory(), "zaofan/Temp/Img/");// 外存根目录下的文件夹
                File dir = new File(lcoalfile.getPath());
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                // 打开照相机
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                currentTime = System.currentTimeMillis();
                // 保存图片时的路径和文件名
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                "zaofan/Temp/Img/" + currentTime + ".jpg")));
                // 跳转去照相
                startActivityForResult(intent, PHOTO_GRAPH);
            }
        });

        holder.mTvUserHeadAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUserHeadPop.dismiss();
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, PHOTO_TYPE);
                startActivityForResult(intent, PHOTO_ZOOM);
            }
        });

        mUserHeadPop.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#70000000")));
        mUserHeadPop.showAtLocation(mLlUserInfo, Gravity.BOTTOM, 0, 0);
        mUserHeadPop.setAnimationStyle(R.style.app_pop);
        mUserHeadPop.setOutsideTouchable(true);
        mUserHeadPop.setFocusable(true);
        mUserHeadPop.update();
        mUserHeadPop.showAsDropDown(mPopView);
    }

    public void showBirthday() {
        if (mTvUserInfoBirhthday.getText().equals("")) {     //未设置生日
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DATE);

            mDatePickerDialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    birthdayStr = year + "-" + (month + 1) + "-" + dayOfMonth;
                    mTvUserInfoBirhthday.setText(birthdayStr);
                }
            }, year, month - 1, day);
//            mDatePicker.setMinDate();
            mDatePickerDialog.show();
        } else {              //已设置生日
            birthdayStr = mTvUserInfoBirhthday.getText().toString();
            mDatePickerDialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    birthdayStr = year + "-" + (month + 1) + "-" + dayOfMonth;
                    mTvUserInfoBirhthday.setText(birthdayStr);
                }
            }, Integer.parseInt(birthdayStr.split("-")[0]), Integer.parseInt(birthdayStr.split("-")[1]) - 1, Integer.parseInt(birthdayStr.split("-")[2]));
//            mDatePicker.setMinDate();
            mDatePickerDialog.show();
        }
    }

    /**
     * 将获得的图片进行裁剪
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, PHOTO_TYPE);
        intent.putExtra("crop", "true");

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);

        intent.putExtra("return-data", true);
        // 截图完成后 进行跳转
        startActivityForResult(intent, IMAGE_RESULT);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 照相后 intent data值为null
        if (requestCode == PHOTO_GRAPH) {
            File file = new File(
                    Environment.getExternalStorageDirectory() + "/zaofan/Temp/Img/" + currentTime + ".jpg");
            startPhotoZoom(Uri.fromFile(file));
        }
        if (data == null)
            return;

        switch (requestCode) {
            case PHOTO_ZOOM:
                // 取到选择的相片
                Uri uri = data.getData();
                // 截图处理
                startPhotoZoom(uri);
                break;
            case IMAGE_RESULT:
                // 取到截图后的bitmap
                Bundle bundle = data.getExtras();
                bmp = bundle.getParcelable("data");

                // 进入这里说明图片被更新了
                // isUpdate = true;

                File tmp = new File(Environment.getExternalStorageDirectory(), "zaofan/Temp/CropImg");
                File dir = new File(tmp.getPath());
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                BufferedOutputStream bos;
                cropfile = new File(Environment.getExternalStorageDirectory() + "/zaofan/Temp/CropImg/"
                        + System.currentTimeMillis() + ".jpg");
                try {
                    bos = new BufferedOutputStream(new FileOutputStream(cropfile.getPath()));
                    bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                    bos.flush();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                presenter.uploadPhoto(cropfile);
                break;
            case 100:
                break;
            case 0:
                return;
        }
    }

    @Override
    public void showSuccess(UserData userData) {
        if (mUserHeadPop != null && mUserHeadPop.isShowing()) {
            mUserHeadPop.dismiss();
        }

        SharedUtil.putString(context, "user", new Gson().toJson(userData));
        Constant.setUserData(userData);
        UserFragment.isNeedRefesh = true;
        Glide.with(this).load(userData.getPhoto()).placeholder(R.drawable.ic_user_head)
                .error(R.drawable.ic_user_head).into(mIvUserInfoHead);
    }

    @Override
    public void showInfoSuccess(UserData userData) {
        if (mUserSexPop != null && mUserSexPop.isShowing()) {
            mUserSexPop.dismiss();
        }
        T.show("修改成功");
        SharedUtil.putString(context, "user", new Gson().toJson(userData));
        Constant.setUserData(userData);
        UserFragment.isNeedRefesh = true;
        this.finish();
    }

    static class ViewHolder {
        @Bind(R.id.tv_user_head_camera)
        TextView mTvUserHeadCamera;
        @Bind(R.id.tv_user_head_album)
        TextView mTvUserHeadAlbum;
        @Bind(R.id.ll_chat_main_memu)
        LinearLayout mLlChatMainMemu;
        @Bind(R.id.tv_user_head_cancel)
        TextView mTvUserHeadCancel;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    static class ViewHolderSex {
        @Bind(R.id.tv_pop_sex_nan)
        TextView mTvPopSexNan;
        @Bind(R.id.tv_pop_sex_nv)
        TextView mTvPopSexNv;
        @Bind(R.id.ll_pop_sex)
        LinearLayout mLlPopSex;
        @Bind(R.id.tv_pop_sex_cancel)
        TextView mTvPopSexCancel;

        ViewHolderSex(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
